package com.boost.tjvm.classload;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.net.URL;
import java.net.URLClassLoader;

/**
 * Created by cai.tian on 2018/1/10.
 *
 * parent
 * ----------------------------------------------------------------------------------------------------------------------------------------------------------
 * MyUrlClassLoad[urls] -->  AppClassLoader(SystemClassLoader)[class path] --> ExtensionClassloader[JRE_HOME/lib/ext] ---> BootStrapClassLoader[JRE_HOME]
 * ----------------------------------------------------------------------------------------------------------------------------------------------------------
 *
 */
public class MyUrlClassLoad  extends BaseClassLoader {
    private final Logger logger = LoggerFactory.getLogger(MyUrlClassLoad.class);
    public MyUrlClassLoad(URL[] urls) {
        super(urls, ClassLoader.getSystemClassLoader());
    }

    @Override
    protected Class<?> loadClass(String name, boolean resolve) throws ClassNotFoundException {
        synchronized (getClassLoadingLock(name)) {
            logger.info("=+++");
            //从父类已经加载的 class 中获取
            Class<?> findClass = findLoadedClass(name);

            if (findClass == null) {
                try {
                    //从父类加载器获取
                    findClass = getParent().loadClass(name);
                } catch (ClassNotFoundException e) {  // NOSONAR
                    // ClassNotFoundException thrown if class not found
                    // from the non-null parent class loader
                }
            }
            if (findClass == null) {
                try {
                    //从 URL 本类的 Class path 中获取
                    findClass = findClass(name);
                } catch (Exception e) { //NOSONAR
                    // NOSONAR
                }
            }
            if (resolve) {
                resolveClass(findClass);
            }
            return findClass;
        }
    }


}
